import time

class SnowflakeIDGenerator:
    def __init__(self, machine_id=1, epoch=0):
        self.machine_id = machine_id
        self.sequence = 0
        self.last_timestamp = -1
        self.epoch = epoch

        if machine_id < 0 or machine_id > 1023:
            raise ValueError("Machine ID must be between 0 and 1023")

    def _current_timestamp(self):
        return int(time.time() * 1000) - self.epoch

    def generate_id(self):
        timestamp = self._current_timestamp()

        if timestamp < self.last_timestamp:
            raise ValueError("Clock moved backwards. Refusing to generate ID.")

        if timestamp == self.last_timestamp:
            self.sequence = (self.sequence + 1) & 4095
            if self.sequence == 0:
                # 等待下一毫秒
                timestamp = self._wait_for_next_timestamp()
        else:
            self.sequence = 0

        self.last_timestamp = timestamp

        # 组装Snowflake ID
        snowflake_id = ((timestamp << 22) | (self.machine_id << 12) | self.sequence)
        return snowflake_id

    def _wait_for_next_timestamp(self):
        timestamp = self._current_timestamp()
        while timestamp <= self.last_timestamp:
            timestamp = self._current_timestamp()
        return timestamp

# 示例用法
# machine_id = 1  # 机器ID，可以根据实际情况设置
# generator = SnowflakeIDGenerator(machine_id)
#
# # 生成Snowflake ID
# snowflake_id = generator.generate_id()
# print(snowflake_id)
